<?php
/**
 * 
 * 
 * @version $Id: CParameter.php,v 1.3 2011-06-17 04:43:21 herve Exp $
 * @copyright 2011
 */
class CParameter extends CParameterArray {

	public $desc;

	public function __construct($headers, $values = null) {
		if ($headers instanceof ParamDescription){
			$this->desc = $headers;
			parent::__construct(null, null);
			// TODO: Multiple columns key !
			$key = null;
			foreach ($this->desc->headers as $header) {
				$this->_headersByMnemonic[$header->header_mnemonic]= array (
					'mnemonic' => $header->header_mnemonic,
					'label' => $header->header_label,
					'index' => $header->column_index,
					'type' => $header->column_type,
					'key' => $header->param_key
				);
				$this->_headersByIndex[$header->column_index]= & $this->_headersByMnemonic[$header->header_mnemonic];
				$this->_columnsValues[$header->header_mnemonic]= new CParameterIndexedList ($header->header_mnemonic);
				if ($header->param_key) $key = $header;
			}
	
			foreach ($this->desc->values as $value) {
				if (isset ($this->_headersByIndex[$value->value_column])) {
					$header= $this->_headersByIndex[$value->value_column];
	
					if (!isset ($this->_rowsValues[$value->value_row]))
						$this->_rowsValues[$value->value_row]= new CParameterIndexedList ($value->value_row);
	
					$this->_rowsValues[$value->value_row][$header['mnemonic']]= $this->convertValue($header, $value);
					$v = $this->_columnsValues[$header['mnemonic']];
					$v[$value->value_row]= $this->_rowsValues[$value->value_row][$header['mnemonic']];
				}
//				Constants::print_var($value->value_row, false);
//				Constants::print_var($key->column_index, false);
//				Constants::print_var($this->_rowsValues[$value->value_row], false);
//				Constants::print_var($this->_rowsValues[$value->value_row][$key->header_mnemonic]);
				if ($key != null)
					$this->_rowsValuesByKey[$this->_rowsValues[$value->value_row][$key->header_mnemonic]] = $this->_rowsValues[$value->value_row];
			}
			
		}else{
			parent::__construct($headers, $values);
		}
	}

	private function convertValue($header, $value) {
		$r= $value->value;

		if ($r == null)
			$r= "";

		if ($r == "" && $header['type'] != "string")
			return null;

		switch ($header['type']) {
			case 'integer' :
				return intval($r, 10);
			case 'float' :
				return floatval($r);
			case 'string' :
				return (string) $r;
			case 'date' :
				return CDateTimeParser::parse($r, "yyyy-MM-dd");
			case 'datetime' :
				return CDateTimeParser::parse($r, "yyyy-MM-dd HH:mm:ss");
			case 'hour' :
				return CDateTimeParser::parse($r, "HH:mm:ss");
			case 'boolean' :
				return strcasecmp($r, "true") == 0;
			default :
				return $r;
		}
		return $r;
	}
	
	public function getDescription()
	{
		return $this->desc;
	}
}
?>
